from flask import Blueprint, render_template, request
from python.model.weather import WeatherData  # 导入 WeatherData 模型
from python.extensions import db  # 导入数据库扩展

# 创建天气数据蓝图
weather_bp = Blueprint('weather', __name__, url_prefix='/weather')

@weather_bp.route('/', methods=['GET'])
def index():
    """天气数据查询首页，设置默认选中值"""
    # 获取所有城市列表（模型字段是 city）
    cities = db.session.query(WeatherData.city).distinct().all()
    cities = [city[0] for city in cities] if cities else []

    # 获取空气质量等级选项
    goods = db.session.query(WeatherData.aqi_level).distinct().all()
    goods = [level[0] for level in goods] if goods else []

    # 设置默认值
    default_urban = '上海'
    default_goods_choice = '良'

    return render_template(
        'menu/query.html',
        cities=cities,
        goods=goods,
        urban=default_urban,
        goods_choice=default_goods_choice,
        total_count=0
    )

@weather_bp.route('/query', methods=['GET'])
def query():
    """天气数据查询：从数据库获取数据并传递给模板"""
    # 1. 获取筛选参数
    urban = request.args.get('urban', '上海')  # 优先取前端传的值，没有则用默认
    goods_choice = request.args.get('goods', '良')  # 优先取前端传的值，没有则用默认

    # 2. 数据库查询
    query = WeatherData.query
    if urban:
        query = query.filter(WeatherData.city == urban)
    if goods_choice:
        query = query.filter(WeatherData.aqi_level == goods_choice)
    results = query.all()

    # 计算记录总数
    total_count = query.count()

    # 3. 整理数据
    data = {
        'date': [],
        'aqi_level': [],
        'low_temperature': [],
        'high_temperature': [],
        'air_quality_index': []
    }
    if results:
        for result in results:
            # 日期处理
            date_str = result.date.strftime('%Y-%m-%d') if hasattr(result.date, 'strftime') else str(result.date)
            data['date'].append(date_str)
            data['aqi_level'].append(result.aqi_level)
            data['low_temperature'].append(result.min_temp)
            data['high_temperature'].append(result.max_temp)
            data['air_quality_index'].append(result.aqi)

    # 4. 获取下拉框选项
    cities = db.session.query(WeatherData.city).distinct().all()
    cities = [city[0] for city in cities] if cities else []

    goods = db.session.query(WeatherData.aqi_level).distinct().all()
    goods = [level[0] for level in goods] if goods else []

    # 5. 传递数据给模板
    return render_template(
        'menu/query.html',
        data=data,
        cities=cities,
        goods=goods,
        urban=urban,
        goods_choice=goods_choice,
        total_count=total_count
    )